package com.inhim.pjhim.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inhim.pjhim.R;
import com.inhim.pjhim.adapter.ProjectListAdapter;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.entity.ProjectListEntity;
import com.inhim.pjhim.entity.ReaderStyle;
import com.inhim.pjhim.entity.ReaderTwo;
import com.inhim.pjhim.entity.ReaderTypeList;
import com.inhim.pjhim.http.MyOkHttpClient;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.StatusBarUtils;
import com.inhim.pjhim.widget.AuthorWidget;

import org.yczbj.ycrefreshviewlib.inter.InterItemView;
import org.yczbj.ycrefreshviewlib.view.YCRefreshView;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Request;

public class ProjectListActivity extends BaseActivity {
    private YCRefreshView ycRefreshView;
    private ReaderStyle.List readerstyle;
    private ReaderTypeList.List readerType;
    private ProjectListAdapter mAdapter;
    private int mPageNum = 1;
    private Boolean refresh = true;
    private int totalPage;
    private Gson gson;
    private String TAG;
    private String mOrder;
    private int mReaderTypeId;
    TextView tv_title_top;
    TextView tv_content;
    TextView tv_section;
    RadioButton tv_new_update;
    RadioButton tv_noramal_sort;
    private ReaderTwo mReaderTwo;
    private AuthorWidget authorWidget;

    @Override
    public Object offerLayout() {
        return R.layout.activity_project_list;
    }

    @SuppressLint("NewApi")
    @Override
    public void onBindView() {
        gson = new Gson();
        ycRefreshView = findViewById(R.id.ycRefreshView);
        View statusBar = findViewById(R.id.statusBarView);
        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
        layoutParams.height = MyApplication.getStatusBarHeight();
        View navigationView = findViewById(R.id.navigationView);
        ViewGroup.LayoutParams navigationlayoutParams = navigationView.getLayoutParams();
        if (StatusBarUtils.isHaveNativBar(this)) {
            navigationlayoutParams.height = MyApplication.getNavigationBarHeight();
        } else {
            navigationlayoutParams.height = 0;
        }
        readerstyle = (ReaderStyle.List) getIntent().getSerializableExtra("ReaderStyle");
        readerType = (ReaderTypeList.List) getIntent().getSerializableExtra("ReaderTypeList");
        TAG = getIntent().getStringExtra("TAG");
        mReaderTypeId = getIntent().getIntExtra("readerTypeId", 0);
        mReaderTwo = (ReaderTwo) getIntent().getSerializableExtra("ReaderTwo");
        mOrder = "asc";
        if (readerType != null || mReaderTwo != null) {
            initAdapter();
        }
        getReaderList();
    }

    @Override
    public void destory() {

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initAdapter() {
        tv_title_top = findViewById(R.id.tv_title_top);
        tv_content = findViewById(R.id.tv_content);
        tv_section = findViewById(R.id.tv_section);
        tv_new_update = findViewById(R.id.tv_new_update);
        tv_noramal_sort = findViewById(R.id.tv_noramal_sort);
        authorWidget = findViewById(R.id.authorWidget);
        setView();
        tv_new_update.setOnClickListener(v -> {
            refresh = true;
            mOrder = "desc";
            getReaderList();
        });
        tv_noramal_sort.setOnClickListener(v -> {
            refresh = true;
            mOrder = "asc";
            getReaderList();
        });
        //CheckBox iv_down=headerView.findViewById(R.id.cb_down);
        //TextView tv_title=findViewById(R.id.tv_title);
        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(v -> finish());
        mAdapter = new ProjectListAdapter(ProjectListActivity.this);
        ycRefreshView.setLayoutManager(new LinearLayoutManager(ProjectListActivity.this));
        ycRefreshView.setEmptyView(R.layout.empty_view_layout);
        ycRefreshView.setAdapter(mAdapter);
        //设置上拉加载更多时布局，以及监听事件
        mAdapter.setMore(R.layout.view_more, () -> {
            //可以做请求下一页操作
            mPageNum++;
            refresh = false;
            getReaderList();
        });
        ycRefreshView.setRefreshListener(() -> {
            mPageNum = 1;
            refresh = true;
            getReaderList();
        });
        mAdapter.setOnItemClickListener(position -> {
            ProjectListEntity.List reader = mAdapter.getAllData().get(position);
            Intent intent;
            if (reader.getType().equals("2")) {
                intent = new Intent(ProjectListActivity.this, VideoActivity.class);
                intent.putExtra("TAG", TAG);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            } else if (reader.getType().equals("3")) {
                intent = new Intent(ProjectListActivity.this, RadioActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            } else {
                intent = new Intent(ProjectListActivity.this, ArticleActivity.class);
            }
            intent.putExtra("ReaderId", reader.getReaderId());
            startActivity(intent);
        });
        ycRefreshView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                final LinearLayoutManager layoutManager = (LinearLayoutManager) ycRefreshView.getRecyclerView().getLayoutManager();
                int pos = layoutManager.findFirstCompletelyVisibleItemPosition();//获取第一个先是的View的索引
                /*if(pos>1){
                    tv_title.setVisibility(View.VISIBLE);
                    tv_title.setText(readerType.getName());
                }else{
                    tv_title.setVisibility(View.INVISIBLE);
                }*/
            }
        });
    }

    private void setView() {
        if (readerType != null && readerType.getAuthor() != null
                && readerType.getAuthor().getName() != null
                && !"".equals(readerType.getAuthor().getName())) {
//            tv_zuozhe.setText("作者：" + readerType.getAuthor().getName());
            authorWidget.setData(readerType.getAuthor().getHeadPortrait(), readerType.getAuthor().getName(),
                    readerType.getAuthor().getArea(), readerType.getAuthor().getSynopsis());
        }
        if (readerType != null) {
            setText(tv_title_top, readerType.getName());
            setText(tv_content, readerType.getSynopsis());
            setText(tv_section, "共" + readerType.getTotal() + "课");
        }
    }

    private void setViews() {
        if (projectEntity != null && projectEntity.getAuthor() != null
                && projectEntity.getAuthor().getName() != null
                && !"".equals(projectEntity.getAuthor().getName())) {
            authorWidget.setData(readerType.getAuthor().getHeadPortrait(), readerType.getAuthor().getName(),
                    readerType.getAuthor().getArea(), readerType.getAuthor().getSynopsis());
        }
        if (mReaderTwo != null) {
            setText(tv_title_top, mReaderTwo.getName());
            setText(tv_content, mReaderTwo.getSynopsis());
            setText(tv_section, "共" + mReaderTwo.getTotal() + "课");
        }
    }

    private void getReaderList() {
        Log.d("zhiqiang", "getReaderList", new Throwable());
        showLoading("加载中");
        HashMap postMap = new HashMap();
        if (readerType != null) {
            postMap.put("readerTypeId", String.valueOf(readerType.getReaderTypeId()));
        } else if (readerstyle != null) {
            postMap.put("readerStyleId", String.valueOf(readerstyle.getReaderStyleValue().getReaderStyleId()));
            postMap.put("readerStyleValueId", String.valueOf(readerstyle.getReaderStyleValue().getReaderStyleValueId()));
        } else if (mReaderTypeId != 0) {
            postMap.put("readerTypeId", String.valueOf(mReaderTypeId));
        }
        //Log.d("zhiqiang","getReaderList",new Throwable());
        String url = Urls.getReaderList(mPageNum, 10, mOrder);
        MyOkHttpClient.getInstance().asyncJsonPostNoToken(url, postMap, new MyOkHttpClient.HttpCallBack() {
            @Override
            public void onError(Request request, IOException e) {
                hideLoading();
            }

            @Override
            public void onSuccess(Request request, String result) {
                hideLoading();
                ProjectListEntity readerLists = gson.fromJson(result, ProjectListEntity.class);
                if (readerLists.getCode() == 0) {
                    totalPage = readerLists.getPage().getTotalPage();
                    if (mAdapter == null) {
                        mAdapter = new ProjectListAdapter(ProjectListActivity.this);
                    }
                    if (refresh) {
                        mAdapter.removeAllHeader();
                        //mAdapter.addHeader(setInterItemView());
                        mAdapter.clear();
                    }
                   /* for (int i = 0; i < readerLists.getPage().getList().size(); i++) {
                        mAdapter.add(readerLists.getPage().getList().get(i));
                    }*/
                    mAdapter.addAll(readerLists.getPage().getList());
                    if (mPageNum >= totalPage && readerType != null) {
                        mAdapter.pauseMore();
                    }
                    if (readerstyle != null) {
                        mAdapter.setReaderStyle(readerstyle);
                    } else if (readerType != null) {
                        mAdapter.setReaderType(readerType);
                    }
                    if (readerType == null && readerLists.getPage().getList().size() > 0) {
                        projectEntity = readerLists.getPage().getList().get(0);
                        setViews();
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private ProjectListEntity.List projectEntity;

    /*private InterItemView setInterItemView(){
        InterItemView interItemView= new InterItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {
                View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_project_type_list_title,parent,false);
                return view;
            }

            @Override
            public void onBindView(View headerView) {
                ImageView iv_title=headerView.findViewById(R.id.iv_title);
                TextView  tv_title_top=headerView.findViewById(R.id.tv_title_top);
                TextView tv_content=headerView.findViewById(R.id.tv_content);
                TextView tv_section=headerView.findViewById(R.id.tv_section);
                TextView tv_new_update=headerView.findViewById(R.id.tv_new_update);
                TextView tv_noramal_sort=headerView.findViewById(R.id.tv_noramal_sort);
                //CheckBox iv_down=headerView.findViewById(R.id.cb_down);
                if(readerType!=null){
                    setText(tv_title_top,readerType.getName());
                    setText(tv_content,readerType.getSynopsis());
                    setText(tv_section,"共"+readerType.getTotal()+"课");
                }
                tv_new_update.setOnClickListener(v -> {
                    refresh=true;
                    mOrder="desc";
                    getReaderList();
                });
                tv_noramal_sort.setOnClickListener(v -> {
                    refresh=true;
                    mOrder="asc";
                    getReaderList();
                });
               *//* iv_down.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    if(isChecked){
                        tv_content.setVisibility(View.VISIBLE);
                    }else {
                        tv_content.setVisibility(View.GONE);
                    }
                });*//*
                //ImageLoaderUtils.setImage(readerType.getIcon(),iv_title);
            }
        };
        return interItemView;
    }*/

    private void setText(TextView textView, String content) {
        if (content != null && textView != null) {
            textView.setText(content);
        }
    }
}
